<?php
namespace Ayhome\Suite\Syncfile;

use think\Controller;
use think\facade\Config;
use think\facade\Env;
use Jaeger\GHttp;

class Index extends Controller  
{
  public function index()
  {
    $web_root = $_SERVER['DOCUMENT_ROOT'];
    $app_root = Env::get('ROOT_PATH');
    $sub_dir =  str_replace($web_root, "", $app_root);

    $cfg = config('suite.');
    $sync_host = $cfg['sync']['remote'];
    if (!$sync_host) return'';
    $this->assign('remote_host', $sync_host);
    $this->assign('local_host', $_SERVER['SERVER_NAME']);

    // $root = Env::get('VENDOR_PATH');
    $views_path = dirname(__FILE__).'/views';


    $assets_path = str_replace($app_root, "", $views_path);
    $assets_path = $sub_dir.$assets_path;
    $assets_path = str_replace('/views', "", $assets_path);
    $assets_path = $assets_path.'/assets';

    $this->assign('root', $root);
    $this->assign('assets_path', $assets_path);
    $this->assign('views_path', $views_path);


    return $this->fetch($views_path.'/index.html');
  }


  public function sync($path = '/',$type = '')
  {
    $cfg = config('suite.');
    $sync_host = $cfg['sync']['remote'];
    if (!$sync_host) return'';
    
    $locals = $this->getLocals($path);
    if ($type == 'sync') {
      return $this->doSuccess('ok',$locals);
    }

    $r = array();
    $remote = $sync_host.'/index.php/suite/syncfile/sync';
    $rt = GHttp::post($remote,[
      'type' => 'sync',
      'path' => $path
    ]);
    $rjson = json_decode($rt,true);
    $r['remotes']['list'] = $rjson['data']['list'];
    $r['remotes']['path'] = $rjson['data']['path'];
    $r['remotes']['paths'] = $rjson['data']['paths'];
    $r['remotes']['virtual_path'] = $rjson['data']['virtual_path'];

    foreach ($locals['list'] as &$k) {
      if ($r['remotes']['list'][$k['name']]) {
        if ($k['size'] != $r['remotes']['list'][$k['name']]['size']) {
          $k['dif'] = 1;
          $k['rsize'] = $r['remotes']['list'][$k['name']]['size'];
          $k['rutime'] = $r['remotes']['list'][$k['name']]['utime'];
        }else{
          $k['dif'] = 0;
          $k['rsize'] = 0;
          $k['rutime'] = 0;
        }
      }
    }

    $r['locals'] = $locals;
    
    return $this->doSuccess('ok',$r);
  }


  function getLocals($path = '/')
  {
    $cfg = config('suite.');
    $sync_host = $cfg['sync']['remote'];
    if (!$sync_host) return'';

    $path = str_replace("//", "/", $path);
    $app_root = Env::get('ROOT_PATH');
    $web_root = $_SERVER['DOCUMENT_ROOT'];
    $current_path = $app_root.$path;
    $current_path = str_replace("//", "/", $current_path);

    $virtual_path = str_replace($web_root, "", $app_root);
    $virtual_path .= $path;
    $virtual_path = str_replace("//", "/", $virtual_path);

    $dirs = scandir($current_path);
    // print_r($dirs);exit();
    $list = array();
    foreach ($dirs as $k) {
      if ($k == '.' || $k == '..')  continue;
      $v = array();
      $file = $current_path.'/'.$k;
      $v['name'] = $k;
      $v['path'] = $file;
      $v['utime'] = date("Y-m-d H:i:s",filemtime($file));

      $fdir = dirname($file).'/';
      $vpath = str_replace(Env::get('ROOT_PATH'), "", $fdir);
      if (!$vpath) $vpath = '/';
      $v['virtual_path'] = $vpath.$k;


      if (!is_dir($file)) {
        $v['size'] = format_byte(filesize($file));
        $v['type'] = '文件';
        $v['dir'] = 0;
      }else{
        
        $v['type'] = '文件夹';
        $v['size'] = '';
        $v['dir'] = 1;
      }
      $list[$k] = $v;
    }
    $vlist = array_column($list,'dir');
    array_multisort($vlist,SORT_DESC,$list);

    $paths_arr = explode("/", $path);
    $paths = array();


    for($i = 0;$i < count($paths_arr);$i++){
      $v = $paths_arr[$i];
      if ($v) {
        $vo = array();
        $vo['name'] = $v;

        $vv = $paths[count($paths)-1]['path'];
        if ($vv) {
          $vo['path'] = $vv.'/'.$v;
        }else{
          $vo['path'] = $v;
        }
        $paths[] = $vo;
      }
    }
    $r = array();
    $r['list'] = $list;
    $r['paths'] = $paths;
    $r['virtual_path'] = $virtual_path;
    $r['path'] = $path;
    return $r;
  }

  public function up($path = '',$type = '')
  {

    $cfg = config('suite.');
    $sync_host = $cfg['sync']['remote'];
    if (!$sync_host) return'';
    $app_root = Env::get('ROOT_PATH');
    $file = Env::get('ROOT_PATH').$path;

    if ($type == 'up') {
      $fcontent = base64_decode($_POST['content']);
      $file = str_replace("//", "/", $file);
      if ($fcontent && file_exists($file)) {
        $rf = file_put_contents($file, $fcontent);
      }
      return $this->doSuccess('ok',$v);
    }

    $content = file_get_contents($app_root.'/'.$path);
    $v = array();

    $remote = $sync_host.'/index.php/suite/syncfile/up';
    $rt = GHttp::post($remote,[
      'type' => 'up',
      'path' => $path,
      'content' => base64_encode($content),
    ]);
    return $this->doSuccess('ok');
    
  }

  public function down($path ='',$type = '')
  {
    $cfg = config('suite.');
    $sync_host = $cfg['sync']['remote'];
    if (!$sync_host) return'';
    if ($type == 'down') {
      $app_root = Env::get('ROOT_PATH');
      $content = file_get_contents($app_root.'/'.$path);
      $v = array();
      $v['path'] = $path;
      // $v['content'] = $content;
      $v['content'] = base64_encode($content);
      return $this->doSuccess('ok',$v);
    }

    

    $remote = $sync_host.'/index.php/suite/syncfile/down';
    $rt = GHttp::post($remote,[
      'type' => 'down',
      'path' => $path
    ]);
    $arr = json_decode($rt,true);
    $fcontent = base64_decode($arr['data']['content']);

    $file = Env::get('ROOT_PATH').$path;
    $file = str_replace("//", "/", $file);
    if ($fcontent && file_exists($file)) {
      $rf = file_put_contents($file, $fcontent);
      var_dump($rf);exit();
    }
    return $this->doSuccess('ok');
  }

  public function doError($msg = ''){
    $resp['code'] = 400;
    $resp['msg'] = $msg;
    $json = json($resp, 200);
    return $json;
  }

  public function doSuccess($msg = '',$data = ''){
    $resp['code'] = 200;
    $resp['msg'] = $msg;
    $resp['data'] = $data;
    $json = json($resp, 200);
    return $json;
  }




}
